<?php

class ServiceAddressModel {

  public function __construct() {
    
  }

  /**
   * 获得指定分类下的子分类的数组
   *
   * @access  public
   * @param   int     $cat_id     分类的ID
   * @param   int     $selected   当前选中分类的ID
   * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
   * @param   int     $level      限定返回的级数。为0时返回所有级数
   * @return  mix
   */
  public function article_cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0) {
    static $res = NULL;

    if ($res === NULL) {
      $data = read_static_cache('service_address_cat_pid_releate');
      if ($data === false) {
        $sql = "SELECT c.*, COUNT(s.cat_id) AS has_children, COUNT(a.article_id) AS aricle_num " .
                ' FROM ' . $GLOBALS['ecs']->table('service_address_cat') . " AS c" .
                " LEFT JOIN " . $GLOBALS['ecs']->table('service_address_cat') . " AS s ON s.parent_id=c.cat_id" .
                " LEFT JOIN " . $GLOBALS['ecs']->table('service_address') . " AS a ON a.cat_id=c.cat_id" .
                " GROUP BY c.cat_id " .
                " ORDER BY parent_id, sort_order ASC";
        $res = $GLOBALS['db']->getAll($sql);
        write_static_cache('service_address_cat_pid_releate', $res);
      } else {
        $res = $data;
      }
    }

    if (empty($res) == true) {
      return $re_type ? '' : array();
    }

    $options = article_cat_options($cat_id, $res); // 获得指定分类下的子分类的数组

    /* 截取到指定的缩减级别 */
    if ($level > 0) {
      if ($cat_id == 0) {
        $end_level = $level;
      } else {
        $first_item = reset($options); // 获取第一个元素
        $end_level = $first_item['level'] + $level;
      }

      /* 保留level小于end_level的部分 */
      foreach ($options AS $key => $val) {
        if ($val['level'] >= $end_level) {
          unset($options[$key]);
        }
      }
    }

    $pre_key = 0;
    foreach ($options AS $key => $value) {
      $options[$key]['has_children'] = 1;
      if ($pre_key > 0) {
        if ($options[$pre_key]['cat_id'] == $options[$key]['parent_id']) {
          $options[$pre_key]['has_children'] = 1;
        }
      }
      $pre_key = $key;
    }

    if ($re_type == true) {
      $select = '';
      foreach ($options AS $var) {
        $select .= '<option value="' . $var['cat_id'] . '" ';
        $select .= ' cat_type="' . $var['cat_type'] . '" ';
        $select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
        $select .= '>';
        if ($var['level'] > 0) {
          $select .= str_repeat('&nbsp;', $var['level'] * 4);
        }
        $select .= htmlspecialchars(addslashes($var['cat_name'])) . '</option>';
      }

      return $select;
    } else {
      foreach ($options AS $key => $value) {
        $options[$key]['url'] = build_uri('article_cat', array('acid' => $value['cat_id']), $value['cat_name']);
      }
      return $options;
    }
  }

  public function get_articleslist() {
    $result = get_filter();
    if ($result === false) {
      $filter = array();
      $filter['keyword'] = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
      if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1) {
        $filter['keyword'] = json_str_iconv($filter['keyword']);
      }
      $filter['cat_id'] = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
      $filter['sort_by'] = empty($_REQUEST['sort_by']) ? 'a.article_id' : trim($_REQUEST['sort_by']);
      $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);

      $where = '';
      if (!empty($filter['keyword'])) {
        $where = " AND a.title LIKE '%" . mysql_like_quote($filter['keyword']) . "%'";
      }
      if ($filter['cat_id']) {
        $where .= " AND a." . $this->get_article_children($filter['cat_id']);
      }

      /* 文章总数 */
      $sql = 'SELECT COUNT(*) FROM ' . $GLOBALS['ecs']->table('service_address') . ' AS a ' .
              'LEFT JOIN ' . $GLOBALS['ecs']->table('service_address_cat') . ' AS ac ON ac.cat_id = a.cat_id ' .
              'WHERE 1 ' . $where;
      $filter['record_count'] = $GLOBALS['db']->getOne($sql);

      $filter = page_and_size($filter);

      /* 获取文章数据 */
      $sql = 'SELECT a.* , ac.cat_name ' .
              'FROM ' . $GLOBALS['ecs']->table('service_address') . ' AS a ' .
              'LEFT JOIN ' . $GLOBALS['ecs']->table('service_address_cat') . ' AS ac ON ac.cat_id = a.cat_id ' .
              'WHERE 1 ' . $where . ' ORDER by ' . $filter['sort_by'] . ' ' . $filter['sort_order'];

      $filter['keyword'] = stripslashes($filter['keyword']);
      set_filter($filter, $sql);
    } else {
      $sql = $result['sql'];
      $filter = $result['filter'];
    }
    $arr = array();
    $res = $GLOBALS['db']->selectLimit($sql, $filter['page_size'], $filter['start']);

    while ($rows = $GLOBALS['db']->fetchRow($res)) {
      $rows['date'] = local_date($GLOBALS['_CFG']['time_format'], $rows['add_time']);

      $arr[] = $rows;
    }
    return array('arr' => $arr, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
  }

  /**
   * 获得指定文章分类下所有底层分类的ID
   *
   * @access  public
   * @param   integer     $cat        指定的分类ID
   *
   * @return void
   */
  public function get_article_children($cat = 0) {
    return db_create_in(array_unique(array_merge(array($cat), array_keys($this->article_cat_list($cat, 0, false)))), 'cat_id');
  }

  /* 上传文件 */

  public function upload_article_file($upload) {
    if (!make_dir("../" . DATA_DIR . "/service_address")) {
      /* 创建目录失败 */
      return false;
    }

    $filename = cls_image::random_filename() . substr($upload['name'], strpos($upload['name'], '.'));
    $path = ROOT_PATH . DATA_DIR . "/service_address/" . $filename;

    if (move_upload_file($upload['tmp_name'], $path)) {
      return DATA_DIR . "/service_address/" . $filename;
    } else {
      return false;
    }
  }   

}